import axios from 'axios'
import {Message} from 'element-ui';
import Vue from 'vue';
axios.defaults.withCredentials=true
axios.interceptors.response.use(response => {
// Do something before response is sent
    if(response.status && response.status==200 && response.data.status ==500){
        Message.error({message:response.data.msg});
        return;
    }
return response;
},error => {
// Do something with response error

if(error.response.status == 403){
    Message.error({message:'权限不足'});
    return;
}
if(error.response.status ==401){
    Message.error({message:'尚未登录'});
    localStorage.removeItem('user');
    return;
}
//return Promise.reject(error);
});
Vue.prototype.$ajax=axios;
export  const initMenu=(router,store)=>{

    axios({
        url:"http://localhost:8081/menu/getMenuByUserID",
        method:"get"
    }).then(function (param) { 
        console.log(param);
        if(store.state.routers.length>0){
            console.log('-------')
            return;
        }
        
        if(param){
            var routes =  formRouters(param.data.object);
            console.log(routes);
            router.options.routes[1].children = routes;
            console.log(router.options.routes[1].children);
            store.commit('initMenu',routes);
        }        
     })
}
export const formRouters = (routers)=>{

    let array = [];
    routers.forEach(element => {
            let children = [];
            if(element.children && element.children instanceof Array){
                children =  formRouters(element.children);
            }
            let r = {
                path:element.path,
                component(resolve){
                    if(element.component.startsWith('User')){
                        require(['../components/' + element.component + '.vue'], resolve)
                    }else if(element.component.startsWith('Role')){
                        require(['../components/' + element.component + '.vue'], resolve)  
                    }
                },
                name:element.name,
                meta:{auth:element.requireAuth==0||element.requireAuth==null?false:true},
                children:children
            }
            array.push(r);   
    });
    return array;
}